import React from "react"
import { useNavigate, useLocation } from "react-router-dom"
import { Button, Form, Input, Card, message } from "antd"
import {
  reqHospitalSetAdd,
  reqHospitalSetUpdate,
} from "@api/hospital/hospitalSets"

export default function HospitalSetAddOrUpdate() {
  // 编程式导航，获取navigate
  const navigate = useNavigate()
  // 使用Form组件的hook useForm.创建form实例. 此时这个form实例是一个没有和任何表单绑定的form实例,需要利用form实例和form表单进行绑定
  const [form] = Form.useForm()
  //利用useLocation获取编辑时传过来的数据 用于修改
  const location = useLocation()
  // console.log(location.state) //编辑传过来的数据
  // 将修改时传入的数据添加上去
  if (location) {
    form.setFieldsValue(location.state)
  }

  // 点击保存时触发的点击事件
  const onFinish = () => {
    const data = form.getFieldsValue()
    async function add() {
      // 请求添加医院设置
      await reqHospitalSetAdd(data)
      navigate("/syt/hospital/hospitalSet")
      message.success("添加医院成功")
    }
    async function update() {
      data.id = (location.state as any).id
      await reqHospitalSetUpdate(data)
      navigate("/syt/hospital/hospitalSet")
      message.success("医院修改成功")
    }
    if (location.state) {
      update()
    } else {
      add()
    }
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo)
  }

  const goBack = () => {
    navigate("/syt/hospital/hospitalSet")
  }

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off">
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "请输入医院名称" }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "请输入医院编号" }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "请输入api基础路径" }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "请输入联系人姓名" }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            {
              required: true,
              message: "请输入合法的联系人手机",
              pattern: /^1[3-9]\d{9}$/, // 正则表达式
            },
          ]}>
          <Input />
        </Form.Item>

        {/* 按钮设置 */}
        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
            保存
          </Button>
          <Button onClick={goBack}>返回</Button>
        </Form.Item>
      </Form>
    </Card>
  )
}
